import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import confusion_matrix,classification_report
def model(x,theta):
    return x.dot(theta)

def sigmoid(z):
    return 1/(1+np.exp(-z))

def cost(h,y):
    m=len(y)
    j=-1/m*np.sum(y*np.log(h)+(1-y)*np.log(1-h))
    return j

def FP(x,theta1,theta2):
    a1=x
    z2=model(a1,theta1)
    a2=sigmoid(z2)
    z3=model(a2,theta2)
    a3=sigmoid(z3)
    return a2,a3

def BP(x,y,theta1,theta2,a2,a3,alpha):
    s3=a3-y
    s2=s3.dot(theta2.T)*(a2*(1-a2))

    m=len(y)
    dt2=1/m*a2.T.dot(s3)
    dt1=1/m*x.T.dot(s2)

    theta2-=alpha*dt2
    theta1-=alpha*dt1
    return theta1,theta2

def grad(x,y,iter0=5000,alpha=0.1):
    m,n=x.shape
    theta1=np.random.randn(n,100)
    theta2=np.random.randn(100,3)
    J=np.zeros(iter0)
    for i in range(iter0):
        a2,a3=FP(x,theta1,theta2)
        J[i]=cost(a3,y)
        theta1,theta2=BP(x,y,theta1,theta2,a2,a3,alpha)
    return theta1,theta2,a3,J

def score(h,y):
    y_=np.argmax(y,axis=1)
    h_=np.argmax(h,axis=1)
    return np.mean(y_==h_)

if __name__ == '__main__':
    x=np.loadtxt('PEPX.txt',delimiter=',')
    y=np.loadtxt('PEPL.txt',delimiter=',')

    np.random.seed(666)
    a=np.random.permutation(len(x))
    x=x[a]
    y=y[a]

    miu=np.mean(x)
    sigma=np.std(x)
    x=(x-miu)/sigma

    X=np.c_[np.ones(len(x)),x]

    y=y-1
    y_onehot=np.zeros((len(x),3))
    for i in range(len(x)):
        y_onehot[i,int(y[i])]=1

    # a=OneHotEncoder()
    # y_onehot=a.fit_transform(y.reshape(-1,1)).toarray()
    #
    # print(y_onehot)

    num=int(0.75*len(x))
    train_x,test_x=np.split(X,[num,])
    train_y,test_y=np.split(y_onehot,[num,])

    theta1,theta2,train_h,J=grad(train_x,train_y)
    plt.plot(J)
    plt.show()

    print(score(train_h,train_y))
    _,test_h=FP(test_x,theta1,theta2)
    print(score(test_h,test_y))

    test_h=np.argmax(test_h,axis=1)
    test_y=np.argmax(test_y,axis=1)

    print(confusion_matrix(test_y,test_h))
    print(classification_report(test_y,test_h))